package yt.demo.appcoresystem.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yt.demo.appcommonbean.exception.LogicException;
import yt.demo.appcommondb.base.BaseService;
import yt.demo.appcommondb.vo.ConditionVO;
import yt.demo.appcoresystem.entity.SystemRoleMenu;
import yt.demo.appcoresystem.mapper.SystemRoleMenuMapper;
import yt.demo.appcoresystem.service.ISystemRoleMenuService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SystemRoleMenuService extends BaseService<SystemRoleMenu, SystemRoleMenuMapper> implements ISystemRoleMenuService {


    @Autowired
    public SystemRoleMenuService(SystemRoleMenuMapper mapper) {
        super(mapper, SystemRoleMenu.class);
    }

    @Override
    protected List<ConditionVO<SystemRoleMenu, ?>> whereConditions(SystemRoleMenu params) {
        return List.of();
    }

    public List<Long> getRoleMenuIds(List<Long> ids) {
        List<SystemRoleMenu> roleMenuList = getList(null, w -> {
            w.in("role_id", ids);
        }, null);
        return roleMenuList.stream()
                .map(SystemRoleMenu::getMenuId)
                .distinct()
                .collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    public void syncRoleMenus(Long roleId, List<Long> menuIds) {

        List<Long> currentMenuIds = getRoleMenuIds(List.of(roleId));

        //计算需要删除和需要添加的菜单
        List<Long> toDelete = currentMenuIds.stream()
                .filter(menuId -> !menuIds.contains(menuId))
                .toList();

        // 计算出需要插入的菜单 ID
        List<Long> toInsert = menuIds.stream()
                .filter(menuId -> !currentMenuIds.contains(menuId))
                .toList();

        // 删除需要删除的关联
        if (!toDelete.isEmpty()) {
            deleteRoleMenus(roleId, toDelete);
        }
        // 批量插入新的关联
        if (!toInsert.isEmpty()) {
            List<SystemRoleMenu> roleMenus = toInsert.stream()
                    .map(menuId -> {
                        SystemRoleMenu systemRoleMenu = new SystemRoleMenu();
                        systemRoleMenu.setRoleId(roleId);
                        systemRoleMenu.setMenuId(menuId);
                        return systemRoleMenu;
                    })
                    .toList();
            if (batchInsert(roleMenus)) {
                throw new LogicException("同步失败");
            }
        }
    }

    public void deleteRoleMenus(Long roleId, List<Long> menuIds) {
        List<ConditionVO<SystemRoleMenu, ?>> conditions = new ArrayList<>();
        conditions.add(ConditionVO.createCondition(SystemRoleMenu::getRoleId, "eq", roleId));
        conditions.add(ConditionVO.createCondition(SystemRoleMenu::getMenuId, "in", menuIds));
        deleteWhere(conditions);
    }
}
